package web

import (
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"rlhs/fr"
)

func LivenessCompareHandler(rw http.ResponseWriter, req *http.Request) {
	lc := fr.NewLivenessCompare()
	var input = map[string]string{
		"image_base64":  req.FormValue("image_base64"),
		"image_url":     req.FormValue("image_url"),
		"video_base64":  req.FormValue("video_base64"),
		"video_url":     req.FormValue("video_url"),
		"validate_data": req.FormValue("validate_data"),
		"liveness_type": req.FormValue("liveness_type"),
		"optional":      req.FormValue("optional"),
	}

	if input["video_base64"] == "" {
		video, _, err := req.FormFile("video_file")
		if err == nil {
			bytes, err := ioutil.ReadAll(video)
			if err != nil {
				log.Print(rw, err.Error())
				return
			}
			videoBase64 := base64.StdEncoding.EncodeToString(bytes)
			input["video_base64"] = videoBase64
		}
	}
	if input["image_base64"] == "" {
		image, _, err := req.FormFile("image_file")
		if err == nil {
			bytes, err := ioutil.ReadAll(image)
			if err != nil {
				log.Print(rw, err.Error())
				return
			}
			imageBase64 := base64.StdEncoding.EncodeToString(bytes)
			input["image_base64"] = imageBase64
		}
	}
	res, err := lc.Recognition(input)
	if err != nil {
		log.Print(rw, err.Error())
		return
	}
	fmt.Printf("%s", res)
	fmt.Fprintf(rw, res)
}
